﻿/*
 * OpenDoPE Word Add-In
 * Copyright (C) 2010-2011  Plutext Pty Ltd
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * 
 * For details, see http://www.gnu.org/licenses/gpl-2.0.html
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using NLog;

using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;


namespace OpenDoPE_Wed
{
    public partial class UiCtrlSimpleConditionMaker : UserControl
    {

        static Logger log = LogManager.GetLogger("OpenDoPE_Wed");

        WedTaskPane taskPane;

        public UiCtrlSimpleConditionMaker(WedTaskPane taskPane)
            //Word.ContentControl currentCC, XmlEditorControl xec)
        {
            this.taskPane = taskPane;

            //this.currentCC = currentCC;
            //this.xec = xec;

            InitializeComponent();
        }

        /// <summary>
        /// Create an XPath and save it to the XPaths part,
        /// then use that XPath to define a new condition.
        /// Note, the XML editor here is displaying the 
        /// user's custom xml part, so they can make their xpath.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonApply_Click(object sender, EventArgs e)
        {
            log.Debug("make simple condition clicked..");

            Word.ContentControl currentCC = taskPane.currentCC;
            // Sanity check
            if (currentCC == null)
            {
                log.Error("currentCC not set?!");
                return;
            }

            if (string.IsNullOrWhiteSpace(this.textBoxConditionID.Text))
            {
                Mbox.ShowSimpleMsgBoxError("You need to choose an ID for the condition");
                return;
            }
            try
            {
                System.Xml.XmlConvert.VerifyNCName(this.textBoxConditionID.Text.Trim());

            }
            catch (System.Xml.XmlException)
            {
                Mbox.ShowSimpleMsgBoxError("Please use an NCName for the Condition ID (hint: no punctuation) ");
                return;
            }


            TagData td = new TagData(currentCC.Tag);
            String existingID = td.get("od:condition");

            if (existingID != null && this.textBoxConditionID.Text.Trim().Equals(existingID))
            {
                // The ID hasn't changed; we silently reuse it
            }
            else
            {
                // They've typed another ID
                // Does it exist already?  
                if (ConditionsPartUtils.getByID(taskPane.conditionsPart, this.textBoxConditionID.Text.Trim()) != null)
                {
                    // If so, overwrite that one, or choose again?
                    // Press OK to overwrite, or cancel to choose another ID
                    if (MessageBox.Show("Press Cancel to type another.", "Condition ID exists", MessageBoxButtons.OKCancel)
                            == DialogResult.Cancel)
                    {
                        return;
                    }
                }
            }


            //////////////////////////
            // First, add the new XPath
            XmlEditorControl xec = taskPane.xmlEditor;
            if (!xec.isWellFormed()) return;
            if (!xec.isInputOK())
            {
                return;
            }
            // Save the part, in case user changed it
            xec.commitChanges();

            // TODO If/when they can get into this form again,
            // need to check whether they are using the same XPath ID as before.
            // what is it?  Either store on entry, or look it up
            // in the condition.


            Office.CustomXMLPart cxp = taskPane.activeCxp;

            // Question
            string questionID = null;
            if (taskPane.questions)
            {
                FormQuestion formQuestion = new FormQuestion(taskPane.questionsPart,
                    xec.xpathTextBox.Text);
                formQuestion.ShowDialog();
                // TODO - handle cancel

                formQuestion.updateQuestionsPart(formQuestion.getQuestion());

                questionID = formQuestion.textBoxQID.Text;
                formQuestion.Dispose();
            }

            // TODO
            string prefixMappings = null;

            // Drop any trailing "/" from a Condition XPath
            string myXpath = xec.xpathTextBox.Text;
            if (myXpath.EndsWith("/")) {
                myXpath = myXpath.Substring(0, myXpath.Length - 1);
                //Mbox.ShowSimpleMsgBoxInfo("truncated to " + myXpath);
            }


            XPathPartUtils.updateXPathsPart(taskPane.xpathsPart,
                myXpath, // xec.xpathTextBox.Text,
                xec.textBoxXPathID.Text.Trim(),
                cxp.Id, prefixMappings, questionID);


            //////////////////////////
            // Second, create and add the condition

            Office.CustomXMLPart conditionsPart = taskPane.conditionsPart;

            xpathref xpath = new OpenDoPE_Wed.xpathref();
            xpath.id = xec.textBoxXPathID.Text.Trim();

            ConditionsPartUtils.updateConditionsPart(conditionsPart, xpath, this.textBoxConditionID.Text);

            //////////////////////////
            // Third, add the condition id to the tag 

            // Write tag
            td.remove("od:repeat");
            td.remove("od:condition");
            td.set("od:condition", this.textBoxConditionID.Text.Trim() );
            currentCC.Tag = td.asQueryString();

            log.Debug("Condition written!");
            Mbox.ShowSimpleMsgBoxInfo("XPath added, Condition created, and content control set to use it :-)");

        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {

            Word.ContentControl currentCC = taskPane.currentCC;

            if (currentCC == null)
            {
                log.Error("currentCC not set?!");
                return;
            }

            // Write tag
            TagData td = new TagData(currentCC.Tag);
            //td.remove("od:repeat");
            td.remove("od:condition");
            currentCC.Tag = td.asQueryString();

            Mbox.ShowSimpleMsgBoxInfo("Condition removed from this content control");

        }
    }
}
